package com.jf.cloud.common.security.adapter;

import cn.hutool.core.util.StrUtil;
import com.jf.cloud.api.auth.bo.UserInfoInTokenBO;
import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.auth.feign.AccountFeignClient;
import com.jf.cloud.api.auth.vo.AuthAccountVO;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.response.ServerResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * @author TRACK
 */
@Component
public class DefaultSignAuthAdapter {
    private static final Logger logger = LoggerFactory.getLogger(DefaultSignAuthAdapter.class);

    @Autowired
    private AccountFeignClient accountFeignClient;

    public ServerResponseEntity<UserInfoInTokenBO> loadUserInfoInToken(Map<String, Object> dataMap) {
        UserInfoInTokenBO userInfoInToken = new UserInfoInTokenBO();
        Object sysType = dataMap.get("sysType");
        if (Objects.isNull(sysType) || Objects.isNull(SysTypeEnum.instance(sysType.toString()))) {
            return ServerResponseEntity.showFailMsg("sysType is empty or wrong");
        }
        SysTypeEnum sysTypeEnum = SysTypeEnum.instance(sysType.toString());
        // 用户端
        if (Objects.equals(sysTypeEnum, SysTypeEnum.ORDINARY)) {
            logger.info("用户端签名验签:{}", dataMap);
            Object userIdObj = dataMap.get("userId");
            if (Objects.nonNull(userIdObj) && StrUtil.isNotBlank(userIdObj.toString())) {
                ServerResponseEntity<AuthAccountVO> response = accountFeignClient.getByUserIdAndType(Long.valueOf(userIdObj.toString()), SysTypeEnum.ORDINARY.value());
                if (!response.isSuccess()) {
                    return ServerResponseEntity.showFailMsg(response.getMsg());
                }
                if (Objects.isNull(response.getData())) {
                    return ServerResponseEntity.showFailMsg("userId is error");
                }
                getUserToken(userInfoInToken, response);
            }
        }
        // 商家
        else if (Objects.equals(sysTypeEnum, SysTypeEnum.MULTISHOP)) {
            logger.info("商家端签名验签:{}", dataMap);
            long shopId = getShopId(dataMap);
            // 默认是店铺超级管理员
            ServerResponseEntity<AuthAccountVO> response = accountFeignClient.getBySysTypeAndIsAdminAndTenantId(SysTypeEnum.MULTISHOP.value(), 1, shopId);
            if (!response.isSuccess()) {
                return ServerResponseEntity.showFailMsg(response.getMsg());
            }
            if (Objects.isNull(response.getData())) {
                return ServerResponseEntity.showFailMsg("shopId is error");
            }
            getTenantUserInfoToken(userInfoInToken, sysTypeEnum, response, shopId);
        }
        // 平台
        else if (Objects.equals(sysTypeEnum, SysTypeEnum.PLATFORM)) {
            logger.info("平台端签名验签:{}", dataMap);
            long sysUserId = getSysUserId(dataMap);
            ServerResponseEntity<AuthAccountVO> response = accountFeignClient.getByUserIdAndType(sysUserId, SysTypeEnum.PLATFORM.value());
            if (!response.isSuccess()) {
                return ServerResponseEntity.showFailMsg(response.getMsg());
            }
            if (Objects.isNull(response.getData())) {
                return ServerResponseEntity.showFailMsg("sysUserId is error");
            }
            getPlatformToken(userInfoInToken, response);
        }
        // 供应商
        else if (Objects.equals(sysTypeEnum, SysTypeEnum.SUPPLIER)) {
            logger.info("供应商端签名验签:{}", dataMap);
            Object supplierIdObj = dataMap.get("supplierId");
            if (Objects.nonNull(supplierIdObj) && StrUtil.isNotBlank(supplierIdObj.toString())) {
                Long supplierId = Long.valueOf(supplierIdObj.toString());
                // 默认是超级管理员
                ServerResponseEntity<AuthAccountVO> response = accountFeignClient.getBySysTypeAndIsAdminAndTenantId(SysTypeEnum.SUPPLIER.value(), 1, supplierId);
                if (!response.isSuccess()) {
                    return ServerResponseEntity.showFailMsg(response.getMsg());
                }
                if (Objects.isNull(response.getData())) {
                    return ServerResponseEntity.showFailMsg("supplierId is error");
                }
                getTenantUserInfoToken(userInfoInToken, sysTypeEnum, response, supplierId);
            }
        }
        // 自提
        else if (Objects.equals(sysTypeEnum, SysTypeEnum.STATION)) {
            logger.info("自提端签名验签:{}", dataMap);
            Object stationIdObj = dataMap.get("stationId");
            if (Objects.nonNull(stationIdObj) && StrUtil.isNotBlank(stationIdObj.toString())) {
                Long stationId = Long.valueOf(stationIdObj.toString());
                // 默认是超级管理员
                ServerResponseEntity<AuthAccountVO> response = accountFeignClient.getBySysTypeAndIsAdminAndTenantId(sysTypeEnum.value(), 1, stationId);
                if (!response.isSuccess()) {
                    return ServerResponseEntity.showFailMsg(response.getMsg());
                }
                if (Objects.isNull(response.getData())) {
                    return ServerResponseEntity.showFailMsg("stationId is error");
                }
                getTenantUserInfoToken(userInfoInToken, sysTypeEnum, response, stationId);
            }
        }
        return ServerResponseEntity.success(userInfoInToken);
    }

    private static long getShopId(Map<String, Object> dataMap) {
        Object shopIdObj = dataMap.get("shopId");
        long shopId = Constant.MAIN_SHOP;
        if (Objects.nonNull(shopIdObj) && StrUtil.isNotBlank(shopIdObj.toString())) {
            shopId = Long.parseLong(shopIdObj.toString());
        }
        return shopId;
    }

    private static long getSysUserId(Map<String, Object> dataMap) {
        Object sysUserIdObj = dataMap.get("sysUserId");
        // 默认是平台超级管理员
        long sysUserId = Constant.SUPER_ADMIN_ID;
        if (Objects.nonNull(sysUserIdObj) && StrUtil.isNotBlank(sysUserIdObj.toString())) {
            sysUserId = Long.parseLong(sysUserIdObj.toString());
        }
        return sysUserId;
    }

    private static void getUserToken(UserInfoInTokenBO userInfoInToken, ServerResponseEntity<AuthAccountVO> response) {
        AuthAccountVO authAccountVO = response.getData();
        userInfoInToken.setUserId(authAccountVO.getUserId());
        userInfoInToken.setUid(authAccountVO.getUid());
        userInfoInToken.setIsAdmin(0);
        userInfoInToken.setUserName(authAccountVO.getUsername());
        userInfoInToken.setSysType(SysTypeEnum.ORDINARY.value());
    }

    private static void getPlatformToken(UserInfoInTokenBO userInfoInToken, ServerResponseEntity<AuthAccountVO> response) {
        AuthAccountVO authAccountVO = response.getData();
        userInfoInToken.setUserId(authAccountVO.getUserId());
        userInfoInToken.setTenantId(Constant.PLATFORM_SHOP_ID);
        userInfoInToken.setUid(authAccountVO.getUid());
        userInfoInToken.setIsAdmin(authAccountVO.getIsAdmin());
        userInfoInToken.setUserName(authAccountVO.getUsername());
        userInfoInToken.setSysType(SysTypeEnum.PLATFORM.value());
    }

    private static void getTenantUserInfoToken(UserInfoInTokenBO userInfoInToken, SysTypeEnum sysTypeEnum, ServerResponseEntity<AuthAccountVO> response, Long tenantId) {
        AuthAccountVO authAccountVO = response.getData();
        userInfoInToken.setUserId(authAccountVO.getUserId());
        userInfoInToken.setTenantId(tenantId);
        userInfoInToken.setUid(authAccountVO.getUid());
        userInfoInToken.setIsAdmin(1);
        userInfoInToken.setUserName(authAccountVO.getUsername());
        userInfoInToken.setIsPassShop(authAccountVO.getIsPassShop());
        userInfoInToken.setSysType(sysTypeEnum.value());
    }
}